<template>
  <div class="middle-options">
    <!-- 多卡片展示区域 -->
    <div v-if="selectedLeafNodes.length > 0" class="cards-container">
      <div 
        v-for="leafNode in selectedLeafNodes" 
        :key="leafNode.id" 
        class="card-item"
      >
        <div class="user-card">
          <!-- 卡片关闭按钮 -->
          <div class="card-close-btn" @click="removeCard(leafNode.id)">
            <el-icon><Close /></el-icon>
          </div>
          
          <!-- 面包屑导航 -->
          <div class="breadcrumb-nav">
            <span 
              v-for="(pathItem, pathIndex) in leafNode.path" 
              :key="pathItem.id"
              class="breadcrumb-item"
            >
              {{ pathItem.name }}
              <span v-if="pathIndex < leafNode.path.length - 1" class="breadcrumb-separator"> > </span>
            </span>
          </div>
          
          <!-- 卡片标题 -->
          <div class="card-title-section">
            <h3 class="card-title">{{ leafNode.name }}</h3>
          </div>
          
          <!-- 卡片内容 -->
          <div class="card-content">
            <!-- 空数据状态 -->
            <template v-if="!leafNode.detail || leafNode.detail.length === 0">
              <div class="empty-state">
                <p class="empty-text">暂无数据</p>
              </div>
            </template>
            
            <!-- 有数据时显示表单 -->
            <template v-else>
              <!-- 遍历API返回的表单项数组 -->
              <div 
                 v-for="formItem in leafNode.detail" 
                 :key="formItem.id" 
                 class="form-item"
               >
                <label class="form-label">{{ formItem.name }}</label>
                
                <!-- type: 0 - 输入框 -->
                <template v-if="formItem.type === 0">
                  <el-input 
                    v-model="leafNode.formData[`item_${formItem.id}_input`]" 
                    placeholder="请输入" 
                    class="form-input"
                  />
                </template>
                
                <!-- type: 1 - 单选 -->
                <template v-else-if="formItem.type === 1">
                  <el-radio-group 
                    v-model="leafNode.formData[`item_${formItem.id}_radio`]" 
                    class="form-radio-group"
                  >
                    <el-radio 
                      v-for="(option, optIndex) in formItem.organScheme?.options || []" 
                      :key="optIndex" 
                      :label="option.value"
                      class="form-radio"
                    >
                      {{ option.value }}
                    </el-radio>
                  </el-radio-group>
                </template>
                
                <!-- type: 2 - 多选 -->
                <template v-else-if="formItem.type === 2">
                  <el-checkbox-group 
                    v-model="leafNode.formData[`item_${formItem.id}_checkbox`]" 
                    class="form-checkbox-group"
                  >
                    <el-checkbox 
                      v-for="(option, optIndex) in formItem.organScheme?.options || []" 
                      :key="optIndex" 
                      :label="option.value"
                      class="form-checkbox"
                    >
                      {{ option.value }}
                    </el-checkbox>
                  </el-checkbox-group>
                </template>
                
                <!-- type: 3 - 输入框带单位 -->
                <template v-else-if="formItem.type === 3">
                  <div class="input-with-unit">
                    <el-input 
                      v-model="leafNode.formData[`item_${formItem.id}_input`]" 
                      placeholder="请输入" 
                      class="form-input"
                    />
                    <span>{{ leafNode.formData[`item_${formItem.id}_unit`] }}</span>
                  </div>
                </template>
                
                <!-- type: 4 - 2个输入框面积计算带单位选择 -->
                <template v-else-if="formItem.type === 4">
                  <div class="area-calculation">
                    <div class="calculation-inputs">
                      <el-input 
                        v-model="leafNode.formData[`item_${formItem.id}_length`]" 
                        placeholder="长度" 
                        class="form-input"
                      />
                      <span class="multiply-symbol">×</span>
                      <el-input 
                        v-model="leafNode.formData[`item_${formItem.id}_width`]" 
                        placeholder="宽度" 
                        class="form-input"
                      />
                      <span class="equals-symbol">=</span>
                      <el-input 
                        :value="calculateArea(leafNode.formData[`item_${formItem.id}_length`], leafNode.formData[`item_${formItem.id}_width`])" 
                        readonly 
                        class="form-input result-input"
                      />
                      <el-radio-group 
                        v-model="leafNode.formData[`item_${formItem.id}_unit`]" 
                        class="unit-radio-group"
                      >
                        <el-radio 
                          v-for="(unit, unitIndex) in formItem.organScheme?.units || []" 
                          :key="unitIndex" 
                          :label="unit.value"
                          class="unit-radio"
                        >
                          {{ unit.value }}
                        </el-radio>
                      </el-radio-group>
                    </div>
                  </div>
                </template>
                
                <!-- type: 5 - 3个输入框体积计算 -->
                <template v-else-if="formItem.type === 5">
                  <div class="volume-calculation">
                    <div class="calculation-inputs">
                      <el-input 
                        v-model="leafNode.formData[`item_${formItem.id}_length`]" 
                        placeholder="长度" 
                        class="form-input"
                      />
                      <span class="multiply-symbol">×</span>
                      <el-input 
                        v-model="leafNode.formData[`item_${formItem.id}_width`]" 
                        placeholder="宽度" 
                        class="form-input"
                      />
                      <span class="multiply-symbol">×</span>
                      <el-input 
                        v-model="leafNode.formData[`item_${formItem.id}_height`]" 
                        placeholder="高度" 
                        class="form-input"
                      />
                      <span class="equals-symbol">=</span>
                      <el-input 
                        :value="calculateVolume(leafNode.formData[`item_${formItem.id}_length`], leafNode.formData[`item_${formItem.id}_width`], leafNode.formData[`item_${formItem.id}_height`])" 
                        readonly 
                        class="form-input result-input"
                      />
                      <el-radio-group 
                        v-model="leafNode.formData[`item_${formItem.id}_unit`]" 
                        class="unit-radio-group"
                      >
                        <el-radio 
                          v-for="(unit, unitIndex) in formItem.organScheme?.units || []" 
                          :key="unitIndex" 
                          :label="unit.value"
                          class="unit-radio"
                        >
                          {{ unit.value }}
                        </el-radio>
                      </el-radio-group>
                    </div>
                  </div>
                </template>
              </div>
              
             </template>
           </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="no-data">
      <el-empty description="请在左侧菜单中选择检查项" />
    </div>
  </div>
</template>


<script setup>
/**
 * 中间选项卡组件 - 显示设置卡片
 * 根据左侧菜单选中的叶子节点，展示对应的配置表单
 */
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { useMedicalStore } from '@/store/medical'
import { House, InfoFilled, Close } from '@element-plus/icons-vue'

const store = useMedicalStore()

// 定义事件发射
const emit = defineEmits(['form-data-change', 'card-removed'])

// 获取选中的叶子节点列表
const selectedLeafNodes = computed(() => store.selectedLeafNodes)

// 加载状态
const loading = ref(false)

// 初始化表单数据
const initializeFormData = (node) => {
  if (!node.formData) {
    node.formData = {}
  }
  
  // 根据API返回的表单项初始化对应的表单数据
  if (node.detail && Array.isArray(node.detail)) {
    node.detail.forEach(formItem => {
      const itemId = formItem.id
      
      // 根据type类型初始化不同的表单字段
      switch (formItem.type) {
        case 0: // 输入框
          if (!node.formData[`item_${itemId}_input`]) {
            node.formData[`item_${itemId}_input`] = ''
          }
          break
        case 1: // 单选
          if (node.formData[`item_${itemId}_radio`] === undefined) {
            node.formData[`item_${itemId}_radio`] = ''
          }
          break
        case 2: // 多选
          if (!node.formData[`item_${itemId}_checkbox`]) {
            node.formData[`item_${itemId}_checkbox`] = []
          }
          break
        case 3: // 输入框带单位
          if (!node.formData[`item_${itemId}_input`]) {
            node.formData[`item_${itemId}_input`] = ''
          }
          if (!node.formData[`item_${itemId}_unit`]) {
            // 从API数据中获取默认单位
            const defaultUnit = formItem.organScheme?.units?.[0]?.value || formItem.organScheme?.unit || ''
            node.formData[`item_${itemId}_unit`] = defaultUnit
          }
          break
        case 4: // 面积计算
          if (!node.formData[`item_${itemId}_length`]) {
            node.formData[`item_${itemId}_length`] = ''
          }
          if (!node.formData[`item_${itemId}_width`]) {
            node.formData[`item_${itemId}_width`] = ''
          }
          if (!node.formData[`item_${itemId}_unit`]) {
            node.formData[`item_${itemId}_unit`] = ''
          }
          break
        case 5: // 体积计算
          if (!node.formData[`item_${itemId}_length`]) {
            node.formData[`item_${itemId}_length`] = ''
          }
          if (!node.formData[`item_${itemId}_width`]) {
            node.formData[`item_${itemId}_width`] = ''
          }
          if (!node.formData[`item_${itemId}_height`]) {
            node.formData[`item_${itemId}_height`] = ''
          }
          if (!node.formData[`item_${itemId}_unit`]) {
            node.formData[`item_${itemId}_unit`] = ''
          }
          break
      }
    })
  }
  
  // 初始化固定字段
  if (!node.formData.name) {
    node.formData.name = ''
  }
  if (!node.formData.accessModules) {
    node.formData.accessModules = []
  }
}

// 面积计算函数
const calculateArea = (length, width) => {
  const l = parseFloat(length) || 0
  const w = parseFloat(width) || 0
  return l && w ? (l * w).toFixed(2) : ''
}

// 体积计算函数
const calculateVolume = (length, width, height) => {
  const l = parseFloat(length) || 0
  const w = parseFloat(width) || 0
  const h = parseFloat(height) || 0
  return l && w && h ? (l * w * h).toFixed(2) : ''
}

// 监听选中的叶子节点变化
watch(selectedLeafNodes, (newNodes) => {
  // 为新选中的节点初始化表单数据
  newNodes.forEach(node => {
    initializeFormData(node)
  })
  // 发射表单数据变化事件
  emit('form-data-change')
}, { deep: true, immediate: true })

// 监听表单数据变化
watch(
  () => selectedLeafNodes.value.map(node => node.formData),
  () => {
    // 发射表单数据变化事件
    emit('form-data-change')
  },
  { deep: true }
)

// 移除卡片并联动左侧菜单
const removeCard = (nodeId) => {
  // 找到要移除的节点信息
  const nodeToRemove = store.selectedLeafNodes.find(node => node.id === nodeId)
  if (nodeToRemove) {
    // 从store中移除节点
    store.removeLeafNode(nodeId)
    
    // 发射事件通知父组件更新左侧菜单
    emit('card-removed', { nodeId, organId: nodeToRemove.organId })
    
    // 发射表单数据变化事件
    emit('form-data-change')
  }
}

// 处理面包屑点击
const handleBreadcrumbClick = (path, index) => {
  // 导航到指定层级
  const targetPath = path.slice(0, index + 1)
  store.navigateToLevel(targetPath.length - 1)
}




</script>

<style scoped>
.middle-options {
  height: 100%;
  background: #f5f5f5;
  padding: 20px;
  overflow-y: auto;
}

/* 卡片容器 */
.cards-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 单个卡片样式 */
.user-card {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
}

.card-close-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #909399;
  transition: color 0.2s ease;
  z-index: 10;
}

.card-close-btn:hover {
  color: #f56c6c;
}

.card-close-btn .el-icon {
  font-size: 14px;
}

/* 面包屑导航 */
.breadcrumb-nav {
  font-size: 12px;
  color: #87ceeb; /* 浅蓝色 */
  margin-bottom: 15px;
  line-height: 1.4;
}

.breadcrumb-item {
  display: inline;
}

.breadcrumb-separator {
  margin: 0 5px;
  color: #b0d4f1; /* 浅蓝色分隔符 */
}

/* 卡片标题 */
.card-title-section {
  margin-bottom: 20px;
}

.card-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e3a8a; /* 深蓝色 */
  line-height: 1.4;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 4px 8px;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

.remove-btn {
  background: rgba(239, 68, 68, 0.8);
  border-color: rgba(239, 68, 68, 0.9);
}

.remove-btn:hover {
  background: rgba(239, 68, 68, 1);
}

/* 卡片内容 */
.card-content {
  /* 内容区域样式 */
}

/* 表单项样式 */
.form-item {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.form-label {
  flex-shrink: 0;
  min-width: 120px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
  line-height: 32px;
  margin: 0;
}



/* 表单控件样式优化 */
.form-input {
  flex: 1;
}

.form-radio-group,
.checkbox-group,
.unit-input-group,
.area-calculation,
.volume-calculation {
  flex: 1;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.checkbox-item {
  margin-right: 0;
  margin-bottom: 5px;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.radio-item {
  margin-right: 0;
  margin-bottom: 5px;
}

.form-checkbox {
  margin-bottom: 8px;
}

.form-checkbox:last-child {
  margin-bottom: 0;
}

/* 输入框带单位样式 */
.input-with-unit {
  display: flex;
  gap: 8px;
  align-items: center;
}

.input-with-unit .form-input {
  flex: 1;
}

.unit-select {
  width: 80px;
  flex-shrink: 0;
}

/* 计算输入框样式 */
.area-calculation,
.volume-calculation {
  width: 100%;
}

.calculation-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.calculation-inputs .form-input {
  width: 80px;
  flex-shrink: 0;
}

.calculation-inputs .result-input {
  background-color: #f5f7fa;
  color: #606266;
}

.multiply-symbol,
.equals-symbol {
  font-weight: bold;
  color: #606266;
  font-size: 16px;
  margin: 0 4px;
}

.calculation-inputs .unit-select {
  width: 70px;
}

/* 单位单选按钮组样式 */
.unit-radio-group {
  display: flex;
  gap: 12px;
  margin-left: 8px;
}

.unit-radio {
  margin-right: 0;
}

.unit-radio :deep(.el-radio__label) {
  font-size: 14px;
  color: #606266;
}

.unit-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

/* 加载状态 */
.loading-state {
  padding: 20px;
  text-align: center;
}

/* 无数据状态 */
.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .middle-options {
    padding: 15px;
  }
  
  .cards-container {
    gap: 15px;
  }
  
  .user-card {
    padding: 15px;
  }
  
  .card-title {
    font-size: 16px;
  }
}

/* 空数据状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-text {
  margin: 0;
  font-size: 14px;
}
</style>